package com.tramp.frame.server.shiro;

import com.google.common.collect.Sets;
import com.tramp.basic.entity.Admin;
import com.tramp.basic.service.AdminService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author chenjm1
 * @since 2017/11/13
 */
@Component
public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private AdminService adminService;

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //用户角色
        Set<String> rolesSet = Sets.newHashSet();
        //用户权限
        Set<String> permsSet = Sets.newHashSet();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(rolesSet);
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        Admin admin = adminService.login(username, password);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(admin, password, getName());

        return info;
    }
}
